package org.ysling.litemall.wx.annotation.support;
/**
 *  Copyright (c) [ysling] [927069313@qq.com]
 *  [litemall-plus] is licensed under Mulan PSL v2.
 *  You can use this software according to the terms and conditions of the Mulan PSL v2.
 *  You may obtain a copy of Mulan PSL v2 at:
 *              http://license.coscl.org.cn/MulanPSL2
 *  THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 *  EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 *  MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 *  See the Mulan PSL v2 for more details.
 */

import org.springframework.util.StringUtils;
import org.ysling.litemall.core.utils.BeanUtil;
import org.ysling.litemall.db.constant.UserConstant;
import org.ysling.litemall.db.domain.LitemallUser;
import org.ysling.litemall.db.service.LitemallUserService;
import org.ysling.litemall.wx.annotation.LoginUser;
import org.ysling.litemall.wx.util.UserTokenManager;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.annotation.Nonnull;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    public static final String LOGIN_TOKEN_KEY = "X-Litemall-User-Token";

    /**保存用户id和用户openId*/
    public static final ConcurrentHashMap<Integer, String> loginUserMap = new ConcurrentHashMap<>();

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(Integer.class)
                && parameter.hasParameterAnnotation(LoginUser.class);
    }

    @Override
    public Object resolveArgument(@Nonnull MethodParameter parameter,
                                  ModelAndViewContainer container,
                                  NativeWebRequest request,
                                  WebDataBinderFactory factory) throws Exception {

        String token = request.getHeader(LOGIN_TOKEN_KEY);
        if (!StringUtils.hasText(token)) {
            return null;
        }
        LitemallUserService userService = BeanUtil.getBean(LitemallUserService.class);
        Integer userId = UserTokenManager.getUserId(token);
        if (userId == null) {
            return null;
        }
        String openid = loginUserMap.get(userId);
        if (openid != null){
            return userId;
        }
        LitemallUser user = userService.findById(userId);
        if (user == null || !Objects.equals(user.getStatus() , UserConstant.STATUS_NORMAL.status)) {
            return null;
        }
        loginUserMap.put(userId , user.getWeixinOpenid());
        return userId;
    }
}
